package com.common.service.impl;

import com.common.dao.AccountInfoDAO;
import com.common.dao.PersonInfoDAO;
import com.common.dao.PrivilegeInfoDAO;
import com.common.dto.AccountInfoDTO;
import com.common.dto.PersonInfoDTO;
import com.common.dto.PrivilegeInfoDTO;
import com.common.service.AccountInfoService;
import com.common.service.PersonInfoService;
import com.common.service.base.BaseService;
import com.common.util.ChangePassword;
import com.common.util.ConstantDefine;
import com.common.util.DateUtil;
import com.common.util.StringUtil;
import com.github.pagehelper.PageInfo;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("personInfoService")
public class PersonInfoServiceImpl extends BaseService<PersonInfoDTO> implements PersonInfoService {

    @Value("${accountKey}")
    private String accountKey;

	@Autowired
	private PersonInfoDAO personInfoDAO;

	@Autowired
	private AccountInfoDAO accountInfoDAO;

    @Autowired
    private PrivilegeInfoDAO privilegeInfoDAO;
    
    @Autowired
    private AccountInfoService accountInfoService;

	private Logger log=Logger.getLogger(PersonInfoServiceImpl.class);

    /**
     * check:phoneNum和accountCode(如果存在：检查mail)
     * @param entity
     * @return
     */
	@Override
	public Map<String, Object> check(PersonInfoDTO entity) {
        Map<String, Object> map = new HashMap<>();
        map.put(ConstantDefine.FLAG,false);
        //accountCode
        String accountCode = entity.getAccountCode();
        if(accountCode == null ){
            map.put(ConstantDefine.FAIL_MSG,"账号为空");
            return map;
        }
        AccountInfoDTO account = new AccountInfoDTO();
        account.setAccountCode(accountCode);
        List<AccountInfoDTO> list1 = accountInfoDAO.select(account);
        if(list1.size() != 0){
            map.put(ConstantDefine.FAIL_MSG,"账号已存在");
            return map;
        }
        String phoneNum = entity.getPhoneNum();
        String mail = entity.getMail();
        if(mail != null){
            PersonInfoDTO personInfo2 = new PersonInfoDTO();
            personInfo2.setPhoneNum(phoneNum);
            List<PersonInfoDTO> list3 = personInfoDAO.select(personInfo2);
            if(list3.size() != 0){
                map.put(ConstantDefine.FAIL_MSG,"邮箱已存在");
                return map;
            }
        }
        map.put(ConstantDefine.FLAG,true);
        return map;
    }

	/**
	 * 查询所有用户信息
	 */
	@Override
	public PageInfo<PersonInfoDTO> selectAllPersonPaging(PersonInfoDTO personInfoDTO, PageInfo<PersonInfoDTO> pageInfo) {
		pageInfo.setList(personInfoDAO.selectAllPerson(personInfoDTO));
		return pageInfo;
	}

    /**
     * 修改用户状态
     */
	@Override
	public Map<String,Object> updateState(PersonInfoDTO personInfoDTO){
		Map<String,Object> result = new HashMap<>();
        PersonInfoDTO temp = personInfoDAO.selectByPrimaryKey(personInfoDTO.getId());
        AccountInfoDTO account = new AccountInfoDTO();
        account.setStatus(personInfoDTO.getStatus());
        account.setPersonCode(temp.getPersonCode());
        accountInfoDAO.updateStateByPersonCode(account);
        //解锁
        if("1".equals(personInfoDTO.getStatus())){
        	accountInfoService.unlock(temp.getPersonCode(), personInfoDTO.getModifier());
        }
        result.put(ConstantDefine.FLAG,true);
		return result;
	}

    /**
     * 根据id查询用户信息
     */
	@Override
	public PersonInfoDTO selectById(PersonInfoDTO personInfoDTO) {
        Map<String,Object> map = new HashMap<>();
        personInfoDTO = personInfoDAO.selectByPrimaryKey(personInfoDTO.getId());
        String personCode = personInfoDTO.getPersonCode();
        //accountCode和roleName
        AccountInfoDTO account = accountInfoDAO.selectRoleNameByPersonCode(personCode);
        personInfoDTO.setAccountCode(account.getAccountCode());
        personInfoDTO.setRoleCode(account.getRoleCode());
        personInfoDTO.setRoleName(account.getRoleName());
        return personInfoDTO;
	}


    /**
     * 2017/07/14
     */
	@Override
	public Map<String, Object>  updateMessage(PersonInfoDTO entity) {
        Map<String, Object> map = new HashMap<>();
        //check:phoneNum和accountCode(如果存在：检查mail)
        Map<String, Object> checkResult = checkForUpdate(entity);
        boolean flag = (boolean) checkResult.get(ConstantDefine.FLAG);
        if(!flag) return checkResult;

        PersonInfoDTO beforePersonInfo = personInfoDAO.selectByPrimaryKey(entity.getId());
        String personCode = beforePersonInfo.getPersonCode();
        entity.setStatus(null);
        String[] t={"status"};
        super.checkAndUpdate(entity, false,t);

        //accountInfo:加密accountPwd
        /*AccountInfoDTO accountInfoDTO = accountInfoDAO.selectByPersonCode(personCode);
        String accountPwd = ChangePassword.changePasswd(accountInfoDTO.getId(), accountInfoDTO.getAccountPwd(), accountKey);
        entity.setAccountPwd(accountPwd);*/
        accountInfoDAO.updateByPersonInfo(entity);

        //修改用户角色
        PrivilegeInfoDTO privilegeInfoDTO = new PrivilegeInfoDTO();
        privilegeInfoDTO.setPersonCode(personCode);
        privilegeInfoDTO.setRoleCode(entity.getRoleCode());
        privilegeInfoDAO.updateByPersonCode(privilegeInfoDTO);

        map.put(ConstantDefine.FLAG,true);
        return map;
	}

    /**
     * 检查更新是否重复
     * @param entity
     * @return
     */
    private Map<String,Object> checkForUpdate(PersonInfoDTO entity) {
        //获取修改前的用户信息
        PersonInfoDTO beforePersonInfo = personInfoDAO.selectByPrimaryKey(entity.getId());
        AccountInfoDTO accountInfoDTO = accountInfoDAO.selectByPersonCode(beforePersonInfo.getPersonCode());
        beforePersonInfo.setAccountCode(accountInfoDTO.getAccountCode());

        Map<String, Object> map = new HashMap<>();
        map.put(ConstantDefine.FLAG,false);
        //accountCode
        String accountCode = entity.getAccountCode();
        if(accountCode == null || "".equals(accountCode)){
            map.put(ConstantDefine.FAIL_MSG,"账号为空");
            return map;
        }
        AccountInfoDTO account = new AccountInfoDTO();
        account.setAccountCode(accountCode);
        List<AccountInfoDTO> list1 = accountInfoDAO.select(account);
        if(!accountCode.equals(beforePersonInfo.getAccountCode()) && list1.size() != 0 ){
            map.put(ConstantDefine.FAIL_MSG,"账号已存在");
            return map;
        }
        //phoneNum
        String phoneNum = entity.getPhoneNum();
        //mail
        String mail = entity.getMail();
        if(mail != null && !"".equals(mail)){
            PersonInfoDTO personInfo2 = new PersonInfoDTO();
            personInfo2.setPhoneNum(phoneNum);
            List<PersonInfoDTO> list3 = personInfoDAO.select(personInfo2);
            if(mail.equals(beforePersonInfo.getMail()) && list3.size() != 0){
                map.put(ConstantDefine.FAIL_MSG,"邮箱已存在");
                return map;
            }
        }

        map.put(ConstantDefine.FLAG,true);
        return map;
    }

    /**
	 * 2017/07/13
	 */
	@Override
	public Map<String, Object> saveMessage(PersonInfoDTO entity) {
        Map<String, Object> map = new HashMap<>();

		//check:phoneNum和accountCode(如果存在：检查mail)
        Map<String, Object> checkResult = check(entity);
        boolean flag = (boolean) checkResult.get(ConstantDefine.FLAG);
        if(!flag) return checkResult;

        String personCode = StringUtil.getUUID();

        //personInfo
        entity.setPersonCode(personCode);
        entity.setRegisterTime(DateUtil.getNowDate());
        int count1 = personInfoDAO.insertSelective(entity);

        //accountInfo
        entity.setId(StringUtil.getUUID());
        String password = ChangePassword.changePasswd(entity.getId(), entity.getAccountPwd(), accountKey);
        entity.setAccountPwd(password);
        int count2 = accountInfoDAO.insertByPersonInfo(entity);

		//添加角色信息
        PrivilegeInfoDTO privilegeInfoDTO = new PrivilegeInfoDTO();
        privilegeInfoDTO.setPersonCode(personCode);
        privilegeInfoDTO.setRoleCode(entity.getRoleCode());
        int count3 = privilegeInfoDAO.insertSelective(privilegeInfoDTO);

        if(count1==0 || count2==0 || count3==0)
            map.put(ConstantDefine.FLAG,false);
        else
            map.put(ConstantDefine.FLAG,true);
		return map;
	}

    /**
     * 2017/07/14
     */
    @Override
    public Map<String, Object> searchPaging(PersonInfoDTO entity) {
        List<PersonInfoDTO> list = personInfoDAO.search(entity);
        for(int index = 0 ; index < list.size(); index++){
            PersonInfoDTO personInfo = list.get(index);
            String personCode = personInfo.getPersonCode();
            AccountInfoDTO accountInfo = accountInfoDAO.selectByPersonCode(personCode);
            String password = ChangePassword.decryptPasswd(accountInfo.getId(), personInfo.getAccountPwd(), accountKey);
            personInfo.setAccountPwd(password);
            list.set(index,personInfo);
        }
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put(ConstantDefine.ROWS, list);
        return resultMap;
    }

    @Override
    public Map<String, Object> deletePersons(List<String> ids) {
        Map<String,Object> map = new HashMap<String,Object>();
        List<String> personCodeList = new ArrayList<>();
        for(int index = 0 ; index < ids.size(); index++){
            PersonInfoDTO personInfoDTO = personInfoDAO.selectByPrimaryKey(ids.get(index));
            String personCode = personInfoDTO.getPersonCode();
            personCodeList.add(personCode);
        }
        personInfoDAO.updateIsDel(personCodeList);
        map.put(ConstantDefine.FLAG,true);
        return map;
    }

    @Override
    public Map<String, Object> deletePerson(PersonInfoDTO entity) {
        Map<String, Object> map = new HashMap<>();
        entity.setStatus("2");
        personInfoDAO.updateByPrimaryKeySelective(entity);
        PersonInfoDTO personInfoDTO = personInfoDAO.selectByPrimaryKey(entity.getId());
        String personCode = personInfoDTO.getPersonCode();
        AccountInfoDTO account = new AccountInfoDTO();
        account.setPersonCode(personCode);
        account.setAudit("2");
        accountInfoDAO.updateStateByPersonCode(account);
        map.put(ConstantDefine.FLAG,true);
        return map;
    }

    @Override
    public PersonInfoDTO selectByPersonCode(String personCode) {
        PersonInfoDTO personInfo = personInfoDAO.selectByPersonCode(personCode);
        return personInfo;
    }

    @Override
    public Map<String, Object> selectByPaging(PersonInfoDTO entity) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        List<PersonInfoDTO> list = personInfoDAO.selectPaging(entity);
        resultMap.put(ConstantDefine.ROWS, list);
        //key=rows value=list
        for (String key:resultMap.keySet()
             ) {
//            System.out.println("key:"+key+"    value="+resultMap.get(key));
        }
        return resultMap;


    }

    @Override
    public PersonInfoDTO findByID(String id) {
        return personInfoDAO.findByID(id);
    }

    @Override
	public PageInfo<PersonInfoDTO> selectCustomPaging(PersonInfoDTO entity) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Map<String, Object> checkUpdate(PersonInfoDTO entity) {
		// TODO Auto-generated method stub
		return null;
	}

    /**
     * 解密：显示明文密码
     * @param list
     * @return
     */
    private List<PersonInfoDTO> decryptAccountPwd(List<PersonInfoDTO> list){
        for(int index = 0 ; index < list.size(); index++){
            PersonInfoDTO personInfo = list.get(index);
            String personCode = personInfo.getPersonCode();
            AccountInfoDTO accountInfo = new AccountInfoDTO();
            accountInfo.setPersonCode(personCode);
            AccountInfoDTO accountTemp = accountInfoDAO.selectByDTO(accountInfo);
            //明文
            String password = ChangePassword.decryptPasswd(accountTemp.getId(), accountTemp.getAccountPwd(), accountKey);
            personInfo.setAccountPwd(password);
            list.set(index,personInfo);
        }
        return list;
    }

}
